package gallery;

import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.diegocarloslima.byakugallery.lib.TileBitmapDrawable;
import com.diegocarloslima.byakugallery.lib.TouchImageView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import gallery.gif.GifView;
import util.bitmap.FileUtil;
import util.bitmap.Img;

public class GalleryFragment extends Fragment {
    private GifView gifView;
    private boolean imageExists;
    private String imagePath = "";
    private String imageUrl;
    private ImageView imageView;
    private String mimeType = "";
    private boolean pause;
    private ProgressBar progress;
    private FrameLayout rootView;
    private SectorProgressView sectorProgressView;
    private TouchImageView touchImageView;

    public GalleryFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        initView();
        if (imageExists) {
            sectorProgressView.setVisibility(View.GONE);
            progress.setVisibility(View.VISIBLE);
            loadPic();
        } else {
            sectorProgressView.setVisibility(View.VISIBLE);
            sectorProgressView.setText("0%");
            progress.setVisibility(View.GONE);
            downloadPic();
        }

        return rootView;
    }

    void initView() {
        rootView = new FrameLayout(getActivity());
        progress = new ProgressBar(getActivity());
        sectorProgressView = new SectorProgressView(getActivity());
        sectorProgressView.setGravity(Gravity.CENTER);
        sectorProgressView.setTextColor(Color.WHITE);
        touchImageView = new TouchImageView(getActivity());
        gifView = new GifView(getActivity());
        imageView = new ImageView(getActivity());
        LayoutParams p1 = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        p1.gravity = Gravity.CENTER;
        rootView.addView(touchImageView, p1);
        rootView.addView(gifView, p1);
        rootView.addView(imageView, p1);
        LayoutParams p2 = new LayoutParams(View.MeasureSpec.makeMeasureSpec(200, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(200, View.MeasureSpec.EXACTLY));
        p2.gravity = Gravity.CENTER;
        rootView.addView(progress, p2);
        rootView.addView(sectorProgressView, p2);
    }

    private void loadPic() {
        progress.setVisibility(View.VISIBLE);
        sectorProgressView.setVisibility(View.GONE);
        if (mimeType.contains("GIF")) {
            touchImageView.setVisibility(View.INVISIBLE);
            imageView.setVisibility(View.INVISIBLE);
            try {
                if (pause) {
                    gifView.showCover();
                } else {
                    gifView.showAnimation();
                }
                gifView.setGifImage(new FileInputStream(imagePath));
            } catch (FileNotFoundException e) {
            }
        } else if (mimeType.contains("BMP")) {
            gifView.setVisibility(View.GONE);
            touchImageView.setVisibility(View.GONE);
            progress.setVisibility(View.VISIBLE);
            //                43e.setVisibility(View.VISIBLE);
            final Img<?> img = new Img<Object>(FileUtil.getCacheDir(), imagePath);
            img.setSizeBaseOnWidth((int) (getResources().getDisplayMetrics().widthPixels * 0.5f));
            img.decodeBitmapAsync(new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    imageView.setImageBitmap(img.getBitmap());
                    progress.setVisibility(View.GONE);
                    //                        sectorProgressView.setVisibility(View.GONE);
                }
            });
        } else if (mimeType.startsWith("IMAGE")) {
            gifView.setVisibility(View.GONE);
            imageView.setVisibility(View.GONE);
            TileBitmapDrawable.attachTileBitmapDrawable(touchImageView, imagePath, null, new TileBitmapDrawable.OnInitializeListener() {
                @Override
                public void onStartInitialization() {
                    progress.setVisibility(View.VISIBLE);
                    //                        sectorProgressView.setVisibility(View.VISIBLE);
                }

                @Override
                public void onEndInitialization() {
                    progress.setVisibility(View.INVISIBLE);
                    //                        sectorProgressView.setVisibility(View.INVISIBLE);
                }
            });
        }
    }

    private void downloadPic() {
        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        init();
                        loadPic();
                        break;
                    case 1:
                        Integer mess = (Integer) msg.obj;
                        int number = mess * 360 / 100;
                        sectorProgressView.setSweep(number);
                        sectorProgressView.setText(mess + "%");
                        break;
                }

            }

            ;
        };
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                File file = new File(imagePath);
                if (file.exists()) {
                    handler.sendEmptyMessage(1);
                    return;
                }
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                URL url = null;
                HttpURLConnection connection = null;
                InputStream is = null;
                FileOutputStream fos = null;
                File tempFile = new File(file.getParent(), file.getName() + ".tmp");
                try {
                    url = new URL(imageUrl);
                    connection = (HttpURLConnection) url.openConnection();
                    fos = new FileOutputStream(tempFile, false);
                    is = connection.getInputStream();
                    long sum = connection.getContentLength();
                    long currentRead = 0;
                    byte[] buffer = new byte[1024 * 32];
                    int index = 0;
                    while (-1 != (index = is.read(buffer))) {
                        currentRead += index;
                        float percentage = currentRead * 1f / sum;
                        Integer p = (int) (percentage * 100);
                        handler.removeMessages(1);
                        handler.obtainMessage(1, p).sendToTarget();
                        fos.write(buffer, 0, index);
                    }
                    fos.flush();
                    fos.close();
                    is.close();
                    tempFile.renameTo(file);
                    handler.sendEmptyMessage(0);
                } catch (Exception e) {
                    e.printStackTrace();
                    file.delete();
                } finally {
                    if (null != connection) {
                        connection.disconnect();
                    }
                }
            }
        });
        thread.start();
    }

    public void setGifPause(boolean b) {
        pause = b;
        if (null == gifView) {
            return;
        }
        if (b) {
            gifView.showCover();
        } else {
            gifView.showAnimation();
        }
    }

    public void setImagePath(String path) {
        imagePath = path;
        imageExists = new File(path).exists();
        if (imageExists) {
            init();
        }
    }

    void init() {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, options);
        mimeType = null == options.outMimeType ? "UNKNOWN" : options.outMimeType.toUpperCase();
    }

    public void setImageUrl(String string) {
        imageUrl = string;
    }
}